package leetcode;

import java.util.HashMap;
import java.util.Map;

//打家劫舍
public class Rob {
    public int rob(TreeNode root) {
        Map<TreeNode,Integer> map = new HashMap<>();
        return dfs(root,map);
    }
    public int dfs(TreeNode root,Map<TreeNode,Integer> map){
        if(root == null) return 0;
        if(map.containsKey(root)){
            return map.get(root);
        }
        int money = root.val;
        if(root.left != null){
            money = money + (dfs(root.left.left,map) + dfs(root.left.right,map));
        }
        if(root.right!= null){
            money = money + (dfs(root.right,map) + dfs(root.right.right,map));
        }
        int money1 = dfs(root.left,map) + dfs(root.right,map);
        int result = Math.max(money,money1);
        map.put(root,result);
        return result;
    }

}
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }